/**
 * 网格类: 要求从控制器中获得json格式的数据
 * 
 * 必备配置项
 * 
 * @config {String} gridId 网格对应的div标识
 * @config {String} entityName 网格数据所对应的Entity类名字
 * 
 * 可选配置项 *
 * @config {bool} hasBbar 是否显示状态条（默认为true，表示显示状态条）
 * @config {int} pageSize 分页长度（默认20）
 * @config {bool} showTopToolbar 是否显示顶部的工具条（默认为false，表示不显示）
 * @config {Object} expander 网格的Meta附加控件,比如复选框或自动编号等(默认为null)
 * @config {bool} checkboxSelectionModel(默认为false,表示不用此模式)
 * @config {String} queryUrl 获取Grid数据的URL地址
 * @config {String} deleteUrl 删除Grid数据的URL地址
 * @config {String[]} specialFields 指定显示的字段，默认为空
 * @config {bool} remoteSort 是否在服务端排序
 * @config {Map} 存储要键/值对应的列表  Map map=new Map(); Map map1=new Map();map1.put("1","1");map.put("dd",map1);
 */

Ext.define('gridView', {
	extend : 'Ext.grid.Panel',
	gridId : 'base-grid',
	region : 'center',
	pageSize : 20,
	hasBbar : true,
	expander : null,
	remoteSort : false,
	dataAutoLoad : true,// 是否自动加载数据
	checkboxSelectionModel : false,
	entityName : '',
	packageName : '',
	entityClassName : '',
	queryUrl : '',
	deleteUrl : '',
	exportUrl : '',
    //renderTo:Ext.getBody(),
	recordPk : new Array(),
	searchFlds : new Ext.util.MixedCollection(),
	recDef : null,
	colModel : null,
	specialFields : [],
	codeMap : null,
	initComponent : function() {

        (this.queryUrl == null || this.queryUrl == '')&&(this.queryUrl = getRootPath()+'/'+this.entityName + '/query.action');
		var metaData = null;
		// 获取对应的列名，和数据模式
		Ext.Ajax.request({
					url : getRootPath()+'/commonController/get_grid_meta.action',
					scope : this,
					async : false,
					params : {
						entityName : this.entityName,
						packageName : this.packageName,
						entityClassName : this.entityClassName
					},
					callback : function(o, s, r) {
						var resp = Ext.decode(r.responseText);
						resp.success&&(metaData = resp.data);

					}
				});

		if (metaData != null) {
			var sm;
			// 选择模式
			this.checkboxSelectionModel?sm = new Ext.selection.CheckboxModel():sm = new Ext.selection.RowModel();
			this.getBaseGridMeta(metaData);
			var store = this.getDataStore();
			var bbar;
			this.bbar?bbar = this.bbar:this.hasBbar?bbar = new Ext.PagingToolbar({
								pageSize : this.pageSize,
								store : store,
								displayInfo : true,
								displayMsg : '显示: {0} - {1} 共 {2} 条',
								emptyMsg : "没有数据"
							}):bbar = null;
			this.id = this.gridId;
			this.store = store;
			this.stateful = true;
			// 收缩/展开按钮
			this.collapsible = false;
			this.multiSelect = true;
			this.stateId = 'stateGrid';
			this.columns = this.colModel;
			this.selModel = sm;
			// this.title = 'Array Grid';
			this.bbar = bbar;
			//this.renderTo = this.renderTo;
			this.viewConfig = {
				stripeRows : true,
				enableTextSelection : true
			};
            if (this.dataAutoLoad)
                this.load();
			// 调用父类方法
			this.callParent(arguments);

		}
	},
	getBaseGridMeta : function(result) {
		var resultLength = result.length;
		if (resultLength == 0) {
			Ext.define('MyData' + this.gridId, {
						extend : 'Ext.data.Model',
						fields : this.recDef,
						idProperty : this.recordPk || 'id'
					});
			this.colModel = cms;
		} else {
			var rs = [], cms = [];
			this.expander&&cms.push(this.expander);
			for (var i = 0; i < resultLength; i++) {
                rs.push({
                    name : result[i].name,
                    type : result[i].type
                });
                if (result[i].hidden || result[i].header == '') {
                    continue;
                } else {
                    // 默认为空则全部加入，如果指定了字段则加入，否则不加入
                    if (this.specialFields.length == 0
                        || this.specialFields.indexOf(result[i].name) != -1) {

                    }

                var oCal = new Object;
                oCal.tooltip = result[i].header;
                oCal.text = result[i].header;
                oCal.dataIndex = result[i].name;
                oCal.type = result[i].type;
                oCal.sortable = result[i].sortable;
                oCal.flex = result[i].fixed;
                oCal.width = result[i].width;
                oCal.hidden = result[i].hidden || result[i].header == '';
                oCal.align = result[i].align;
                oCal.sortByField = result[i].sortByField;
                oCal.attributes= result[i].attributes;
                switch (result[i].type) {
					case "date" :
                          //添加显示列
                        oCal.renderer = function(value, metaData, record) {
                                        // 时间格式比较另类，不能直接通过value获取对应的值，所以使用下面的方法获取
                                        var varDate = new Date(record.raw[metaData.column.dataIndex]);
                                        if (record.raw[metaData.column.dataIndex])
                                            return varDate.format(metaData.column.attributes);
                                        else
                                            return "";
                            };
						break;
                    case   "code":
                        // 获取对应的列名，和数据模式
                        if(result[i].attributes!=null && result[i].attributes!=""){
                        	 var codeData = null;
                            Ext.Ajax.request({
                                url : getRootPath()+"/commonController/getCodeValue.action",
                                scope : this,
                                async : false,
                                params : {
                                    type : "code",
                                    codeName : result[i].attributes
                                },
                                callback : function(o, s, r) {
                                    var resp = Ext.decode(r.responseText);
                                    codeData = resp.rows;
                                    if (resp.success && codeData!=null) {
                                        codeData = resp.rows;
                                        if (this.codeMap == null ) {
                                            this.codeMap = new Map();
                                            var map = new Map();
                                            var len = codeData.length;
                                            for (var k = 0; k < len; k++) {
                                                map.put(codeData[k].itemValue.toString(),
                                                    codeData[k].itemText);
                                            }
                                            this.codeMap.put(result[i].attributes, map);
                                        } else {
                                            var map = new Map();
                                            var len = codeData.length;
                                            for (var k = 0; k < len; k++) {
                                                map.put(codeData[k].itemValue.toString(),
                                                    codeData[k].itemText);
                                            }
                                            this.codeMap.put(result[i].attributes, map);
                                        }
                                    }
                                }
                            });
                        }
                        oCal.renderer = function(value, metaData, record) {
                            var codeList = this.codeMap
                                .get(metaData.column.attributes);
                            if (codeList && (value!=null)) {
                                //考虑到多选形式所以使用循环来获取数据
                                var returnValue = "";
                                var str = value.toString().split(",");
                                for (i = 0,len=str.length; i < len; i++) {
                                    returnValue += codeList.get(str[i])+ ",";
                                }
                              return  (returnValue.length>0)?  returnValue.substring(0,returnValue.length-1): returnValue;

                            } else
                                return "";
                        };
                               break;
                    case   "checkcolumn":
                        oCal.xtype= 'checkcolumn'
                        oCal.disabled=true;
                        break;
                    case"entity":
                        // value是个对象
                        var showField=	 result[i].attributes.split(',');
                        for(k=0,l=showField.length;k<l;k++){
                        	var field=showField[k].split(':');
                        	if(k==0){
                        		//
                        		oCal.attributes=(field.length==1? field[0] : field[1]);
                        	}
                        	else{
                        		//
                                rs.push({
                                    name : field[1],
                                    type : result[i].type
                                });
                                //添加实体其它属性
                        		  var oCalEntity = new Object;
                        		  oCalEntity.text =field[0];
                        		  oCalEntity.dataIndex =field[1];
                        		  oCalEntity.attributes= result[i].name+'.'+field[1];
                        		  oCalEntity.tooltip = field[0];
                        		  oCalEntity.sortable = result[i].sortable;
                        		  oCalEntity.align = result[i].align;
                        		  oCalEntity.renderer = function(value, metaData, record) {
                        				 return eval("record.data."+metaData.column.attributes);    
                                  }
                                  cms.push(oCalEntity);
                        	}
                        }
                        oCal.renderer = function(value, metaData, record) {
                        	 return value[metaData.column.attributes];                               
                        };
                        break;
                    default :

						break;
				}
                cms.push(oCal);
			}
            }
			Ext.define('MyData' + this.gridId, {
						extend : 'Ext.data.Model',
						fields : rs,
						idProperty : this.recordPk || 'id'
					});
			this.colModel = cms;

		}

	},
	getDataStore : function() {
        //先判断是否使用了 getRootPath()方法
        var url=((this.queryUrl.indexOf('http://')>-1)?this.queryUrl:(getRootPath()+'/'+this.queryUrl));
        //再判断是否启用了路径
        url=((this.queryUrl.indexOf('../')>-1)?this.queryUrl:url);
		var datastore = new Ext.data.Store({
					model : 'MyData' + this.gridId,
					autoLoad : false,
					pageSize : this.pageSize,
					remoteSort : this.remoteSort,
					proxy : {
						type : 'ajax',
						url :url,
						getMethod : function() {
							return 'POST';
						},// 亮点，设置请求方式,默认为GET
						reader : new Ext.data.reader.Json({
									root : 'rows',
									totalProperty : 'totalCount',
									id : this.recordPk || 'id'
								})
					}
					,sorters: { property: this.recordPk[0], direction: 'DESC' } //如果grid左边是个树，那么排序的时候不知道为什么，会窜id
				});
		return datastore;
	},
	load : function() {
		this.executeQuery();
	},
	/**
	 * 快速查询，需传递主键名和主键的值
	 */
	executeQueryBy : function(keyField, keyValue) {
		var p = new Object();
		p[keyField] = keyValue;
		// extjs4.0以上用this.store.proxy.extraParams
		this.store.proxy.extraParams = p;
		if (this.hasBbar) {
			this.store.load({
						callback : this.afterExecuteQuery,
						scope : this,
						params : {
							page : 0,
							limit : this.pageSize
						}
					});
		} else {
			this.store.load({
						callback : this.afterExecuteQuery,
						scope : this
					});
		}
	},
	queryByBaseParams : function(baseParams) {
		// extjs4.0以上用this.store.proxy.extraParams
		this.store.proxy.extraParams = baseParams;
		if (this.hasBbar) {
			this.store.load({
						callback : this.afterExecuteQuery,
						scope : this,
						params : {
							page : 1,
							limit : this.pageSize
						}
					});
		} else {
			this.store.load({
						callback : this.afterExecuteQuery,
						scope : this
					});
		}
	},getQueryParams:function (){
		var p = new Object();
        var params = new Object();
		var qf = this.searchFlds;
		for (var i = 0, len = qf.keys.length; i < len; i++) {
			var fld = qf.items[i];
			if (fld.getXType() == 'datefield' ) {
				p[qf.keys[i]] = fld.getRawValue();
			}  else  {
				p[qf.keys[i]] = fld.getValue();
			}
//			if(fld.getXTypes().indexOf('combo')>0){
//				 params[qf.keys[i]]='combo';
//			}else{
				 params[qf.keys[i]]=fld.getXType();
			//}
           
		}
        p['pageParams']=Ext.JSON.encode(params);
        return p;
	},
	executeQuery : function() {
		
        // extjs4.0以上用this.store.proxy.extraParams
		this.store.proxy.extraParams = this.getQueryParams();
		this.getStore().currentPage = 1;
		if (this.hasBbar) {
			this.store.load({
						callback : this.afterExecuteQuery,
						scope : this,
						params : {
							page : 1,
							limit : this.pageSize
						}
					});
		} else {
			this.store.load({
						callback : this.afterExecuteQuery,
						scope : this
					});
		}
		
	},
	afterExecuteQuery : function(r, options, success) {
		if (!success) {
		
			//Ext.Msg.alert('错误',this.store.getProxy().getReader().rawData.message);
		}
	},
	goToPrevRecord : function() {
		if (this.getStore().getCount() == 1) {
			this.reSelectCurrent();
		} else {
			this.getSelectionModel().selectPrevious(false);
		}

	},
	goToNextRecord : function() {
		if (this.getStore().getCount() == 1) {
			this.reSelectCurrent();
		} else {
			this.getSelectionModel().selectNext(false);
		}

	},
	reSelectCurrent : function() {
		var crt = this.getSelectionModel().getSelection();
		this.getSelectionModel().clearSelections();
		this.getSelectionModel().setLastFocused([crt]);
	},
	reloadRecords : function() {
		this.getStore().removeAll();
		this.getStore().reload();
	},
	deleteRecord : function() {
		if (this.getSelectionModel().getCount() < 1) {
			Ext.Msg.show({
						title : '',
						msg : '没有选择数据，无法删除。',
						buttons : Ext.Msg.OK,
						fn : this.execute_delete,
						icon : Ext.MessageBox.WARNING
					});
		} else {
			Ext.Msg.show({
						title : '删除确认',
						msg : '真的要删除这条数据吗?',
						buttons : Ext.Msg.YESNO,
						fn : this.execute_delete,
						scope : this,
						icon : Ext.MessageBox.QUESTION
					});
		}
	},
	execute_delete : function(btn) {
		if (btn == 'yes') {
			if (this.deleteUrl == null || this.deleteUrl == '') {
				return;
			}
			var selected = this.getSelectionModel().getSelection();
			//把哟删除的数据整合到一个数组里，所以提交到后台的是一个List
            var pk = new Object();
			for (var k = 0,len=selected.length; k < len; k++) {
				for (var i = 0,len1=this.recordPk.length; i <len1 ; i++) {
                    var li;
                    if(pk[this.recordPk[i]])
                        li=pk[this.recordPk[i]];
                     else{
                        li=new Array();
                        pk[this.recordPk[i]]=li;
                    }
                    li.push(selected[k].get(this.recordPk[i]));
				}
			}
            var url=((this.deleteUrl.indexOf('http://')>-1)?this.deleteUrl:(getRootPath()+'/'+this.deleteUrl));
            //再判断是否启用了路径
            url=((this.deleteUrl.indexOf('../')>-1)?this.deleteUrl:url);
                Ext.Ajax.request({
                    url : url,
                    success : function(response, options) {
                            var resp = Ext
                                .decode(response.responseText);
                            if (resp.success) {
                                this.executeQuery();
                                if(this.departmentTree){
                                    Ext.getCmp(this.departmentTree).getStore().reload();
                                }
                            } else {
                                if (resp.message) {
                                    Ext.Msg.alert('错误', resp.message);
                                } else {
                                    Ext.Msg.alert('错误', '删除时服务器端发生错误！');
                                }
                            }
                    },
                    scope : this,
                    params : pk
                });
		}
	},
	after_execute_delete_success : function(response, options) {
		var resp = Ext.decode(response.responseText);
		if (resp.success) {
			var removed = this.getSelectionModel().getSelection();
			this.getStore().find('id', options.params.id);
			// this.getStore().remove(removed);
			// this.getStore().commitChanges();
		} else {
			if (resp.message) {
				Ext.Msg.alert('错误', resp.message);
			} else {
				Ext.Msg.alert('错误', '删除时服务器端发生错误！');
			}
		}
	},
	// 用于打印,生成HTML文档
	exportHtml : function() {
		this.exportList("html");
	},
	// 导出到Excle文档
	exportExcel : function() {
		this.exportList("xls");
	},
	exportList : function(p_format) {
		
		// 过滤条件
		var qs = '';
        var params = new Object();
		var qf = this.searchFlds;
		for (var i = 0, len = qf.keys.length; i < len; i++) {
			var fld = qf.items[i];
				qs = qs + '&' + qf.keys[i] + '=' + fld.getRawValue();
				 params[qf.keys[i]]=fld.getXType();
           
		}
        qs+='&pageParams='+Ext.JSON.encode(params);
		
		
		// 当前显示的字段
		var cs = '&fieldsList=';
		var f = [];
		for (var i = 0,len=this.columns.length; i <len ; i++) {
			if (!this.columns[i].isHidden()) {
				f.push(this.columns[i].dataIndex);
			}
		}
		cs = cs + '' + f.join('-');
		// 当前排序字段以及排序顺序(asc,desc)
		var ss = ''; // 此处仅考虑排序，不涉及分组的问题
		if (this.getStore().sorters.items.length>0) {
			ss = '&sort=' + this.getStore().sorters.items[0].property + '&dir='
					+ this.getStore().sorters.items[0].direction;
		}
		 var url=((this.exportUrl.indexOf('http://')>-1)?this.exportUrl:(getRootPath()+'/'+this.exportUrl));
//		 Ext.Ajax.request({
//             url : url,
//             params:this.getQueryParams(),
//             success : function(response, options) {
//                     var resp = Ext.decode(response.responseText);
//                     if (resp.success) {
//                        
//                     } else {
//                         if (resp.message) {
//                             Ext.Msg.alert('错误', resp.message);
//                         } else {
//                             Ext.Msg.alert('错误', '删除时服务器端发生错误！');
//                         }
//                     }
//             },
//             scope : this
//         });
		var v = window.open(	url + "?export=y&_p_exp_format="
								+ ((p_format) ? p_format : "xls") + qs + cs
								+ ss, 'Export',
						'adress=no,width=710,height=450,scrollbars=yes,resizable=yes,menubar=yes');
		v.focus();
	}
});

// Ext.define('Divo.Base.GridView', Divo.Base.GridView);
